package controllers;

import java.awt.Desktop;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.io.File;
import files.Save;
import Entity.Book;
import Entity.BorrowRecored;

import messagesPacks.BookOrderMessage;
import messagesPacks.BookSubjectMessage;
import messagesPacks.RequestTOCMessage;
import messagesPacks.SubExtendBorrowMessage;
import messagesPacks.SubscriberBorrowDataMessage;
import messagesPacks.SubscriberSearchBookMassege;
import messagesPacks.SubscriberUpdateProfileMessage;
import messagesPacks.TOCMessage;
import messagesPacks.ViewHistoryMessage;


public class SubscriberUIP implements Observer 
{
   static ChatClient client;
	
	public SubscriberUIP()
	{
		System.out.println("SubscriberUIP Created.");
		WelcomeUIP.client.addObserver(this);
		SubscriberUIP.client = WelcomeUIP.client;
	}

	
	/**
	 * @author Roman
	 * @Data 28.12.12
	 * @return value :BookSubjectsMSG
	 */
	public BookSubjectMessage getSubjectsOfBooks()
	{
		BookSubjectMessage BookSubject_msg = new BookSubjectMessage();
	try
	{
		System.out.println("Sending SearchByBookSubjectMSG & WAITING..");
		client.setMaxRetries(2);
		client.setWaitTime(6000);
		Object return_obj = null;
		return_obj = client.sendToServerAndWait(BookSubject_msg, BookSubject_msg);
		 
		if (return_obj==null)
		{
			// Timeout OR error in transmit.
			System.out.println("UIP: (NULL) in getSubjectsOfBooks() ");
			return null;
		}
		else
		{
			return (BookSubjectMessage)return_obj;
		}
	 }
	 catch (Exception e) 
	 {
			System.out.println("UIP: EXCEPTION in getSubjectsOfBooks() ");
			e.printStackTrace();
			return null;
	 }
	
   }

	//=============================================================================================	
		/**
		 * @author Roman Faktorovich
		 * @return the resualt if the update succeded
		 *  values : 1 success , 0 failure
		 */
		public int updateSubProfile(String subId,String password ,String phone,String email , String address )
		{

			SubscriberUpdateProfileMessage Update_msg = new SubscriberUpdateProfileMessage(subId ,password , address , email ,phone);
	
			try
			{
				System.out.println("Sending UpdateSuscriberProfileMSG & WAITING..");
				client.setMaxRetries(2);
				client.setWaitTime(6000);
				Object return_obj = null;
				return_obj = client.sendToServerAndWait(Update_msg, Update_msg);
				 
				if (return_obj==null)
				{
					// Timeout OR error in transmit.
					System.out.println("UIP: (NULL) in UpdateSuscriberProfile() ");
					return 0;
				}
				else
				{
					SubscriberUpdateProfileMessage SUPM = (SubscriberUpdateProfileMessage)return_obj;
					return SUPM.getUpdateResult();
				}
			 }
			 catch (Exception e) 
			 {
					System.out.println("UIP: EXCEPTION in UpdateSuscriberProfile() ");
					e.printStackTrace();
					return 0;
			 }
		}
	//=============================================================================================	
		/**
		 * @author Roman Faktorovich
		 * @return the result if the search query succeed
		 *  values : 1 success , 0 failure
		 */
		public SubscriberSearchBookMassege subscriberSearchBook(String book_name , String book_author, String book_subject ,String book_subject_id , String free_text )
		{
			SubscriberSearchBookMassege result_search_msg = new SubscriberSearchBookMassege();

		//if the user didn't fill any details about the searched book 
		  if(book_name.isEmpty() && book_author.isEmpty() && book_subject.equals("Please select subject...") && free_text.isEmpty() )
			  return null;
		  
		  SubscriberSearchBookMassege search_msg = new SubscriberSearchBookMassege();

		  search_msg.getBook().setBookName(book_name);
		  search_msg.getBook().setBookAuthor(book_author);
		  
		 if( !book_subject.equals("Please select subject...") ) 
		   {
			 search_msg.getBook().setBookSubject(book_subject);
		     search_msg.getBook().setBookSubjectID(book_subject_id);
		   }
		 else
		 {
			 search_msg.getBook().setBookSubject("");
		     search_msg.getBook().setBookSubjectID(""); 
			 
		 }
		  search_msg.setFreeText(free_text);

		  try
			{
				System.out.println("Sending SubscriberSearchBookMassege & WAITING..");
				client.setMaxRetries(2);
				client.setWaitTime(6000);
				Object return_obj = null;
				return_obj = client.sendToServerAndWait(search_msg, search_msg);
				 
				if (return_obj==null)
				{
					// Timeout OR error in transmit.
					System.out.println("UIP: (NULL) in scriberSearchForBook() ");
					result_search_msg .setQueryResult(0);
					return result_search_msg;
				}
				else
				{
					return (SubscriberSearchBookMassege)return_obj; 
				}
			 }
			 catch (Exception e) 
			 {
					System.out.println("UIP: EXCEPTION in SubscriberSearchForBook ");
					e.printStackTrace();
					result_search_msg .setQueryResult(0);
					return result_search_msg;
			 }

		}
//=============================================================================================	
		/**
		 * @author Roman Faktorovich
		 * This method orders a book 
		 * @return the result if the search query succeed
		 *  values :2 the order already exist for this user with this ISBN ,
		 *  		  1 success in order , 0 failure in query
		 */
		public int OrderAbook(String subID , String ISBNtoOrder )
		{
			
			BookOrderMessage order_msg = new BookOrderMessage(subID,ISBNtoOrder);
			
			  try
				{
					System.out.println("Sending SubscriberOrderAbookMassege & WAITING..");
					client.setMaxRetries(2);
					client.setWaitTime(6000);
					Object return_obj = null;
					return_obj = client.sendToServerAndWait(order_msg, order_msg);
					 
					if (return_obj==null)
					{
						// Timeout OR error in transmit.
						System.out.println("UIP: (NULL) in OrderAbook() ");
						return 0;
					}
					else
					{
						BookOrderMessage res = (BookOrderMessage)return_obj;
						return res.getResultOforder(); 
					}
				 }
				 catch (Exception e) 
				 {
						System.out.println("UIP: EXCEPTION in OrderAbook ");
						e.printStackTrace();
						return 0;
				 }

		}
		
//=============================================================================================	
		public ViewHistoryMessage viewSubscriberHistory(String userID)
		{
			ViewHistoryMessage history_msg = new ViewHistoryMessage();

			history_msg.setUserID(userID);
		
			  try
				{
					System.out.println("Sending viewSubscriberHistoryMassege & WAITING..");
					client.setMaxRetries(2);
					client.setWaitTime(6000);
					Object return_obj = null;
					return_obj = client.sendToServerAndWait(history_msg, history_msg);
					 
					if (return_obj==null)
					{
						// Timeout OR error in transmit.
						System.out.println("UIP: (NULL) in viewSubscriberHistory() ");
						history_msg.msg_result = -1;
						return history_msg;
					}
					else
					{
						return  (ViewHistoryMessage)return_obj;
					}
				 }
				 catch (Exception e) 
				 {
						System.out.println("UIP: EXCEPTION in viewSubscriberHistory ");
						e.printStackTrace();
						history_msg.msg_result = -1;
						return history_msg;
				 }
	    
		}
//=============================================================================================		
		public SubscriberBorrowDataMessage showBorrows(String userID)
		{
			SubscriberBorrowDataMessage ExtBorrow_msg = new SubscriberBorrowDataMessage();
			
			ExtBorrow_msg.user.setID(userID);
			  try
				{
					System.out.println("Sending SubscriberExtendBorrowMessage & WAITING..");
					client.setMaxRetries(2);
					client.setWaitTime(6000);
					Object return_obj = null;
					return_obj = client.sendToServerAndWait(ExtBorrow_msg, ExtBorrow_msg);
					 
					if (return_obj==null)
					{
						// Timeout OR error in transmit.
						System.out.println("UIP: (NULL) in showBorrows() ");
						ExtBorrow_msg.msg_result = -1;
						return ExtBorrow_msg;
					}
					else
					{
						return  (SubscriberBorrowDataMessage)return_obj;
					}
				 }
				 catch (Exception e) 
				 {
						System.out.println("UIP: EXCEPTION in SubscriberExtendBorrowMessage ");
						e.printStackTrace();
						ExtBorrow_msg.msg_result = -1;
						return ExtBorrow_msg;
				 }
			
			
		}
		
//=============================================================================================		
	public SubExtendBorrowMessage extendSubscriberBorrow(BorrowRecored br) 
	{
		SubExtendBorrowMessage Ex_msg = new SubExtendBorrowMessage();
	
		Ex_msg.Br = br;

		try {
			System.out.println("Sending extendSubscriberBorrow & WAITING..");
			client.setMaxRetries(2);
			client.setWaitTime(6000);
			Object return_obj = null;
			return_obj = client.sendToServerAndWait(Ex_msg, Ex_msg);

			if (return_obj == null) 
			{
				// Timeout OR error in transmit.
				System.out.println("UIP: (NULL) in extendSubscriberBorrow() ");
				Ex_msg.msg_result = -1;
				return Ex_msg;
			} 
			else
			{
				Ex_msg = (SubExtendBorrowMessage) return_obj;
				return Ex_msg;
			}
		}
		catch (Exception e)
		{
			System.out.println("UIP: EXCEPTION in extendSubscriberBorrow ");
			e.printStackTrace();
			Ex_msg.msg_result = -1;
			return Ex_msg;
		}

	}
	
//=============================================================================================	
	public static TOCMessage requestTOC(String isbn)
	{
		// Prepare request message
		RequestTOCMessage request_toc_msg = new RequestTOCMessage();
		request_toc_msg.setIsbn(isbn);
		
		// Prepare return message
		TOCMessage toc_msg = new TOCMessage();
		toc_msg.setSuccess(false);
		
		try
		{
			System.out.println("Sending request for TOC & WAITING..");
			client.setMaxRetries(2);
			client.setWaitTime(6000);
			Object return_obj = null;
			return_obj = client.sendToServerAndWait(request_toc_msg, toc_msg);
			 
			if (return_obj==null)
			{
				// Timeout OR error in transmit.
				System.out.println("UIP: (NULL) in requestTOC() ");
				return toc_msg;
			}
			else
			{
				TOCMessage toc = (TOCMessage)return_obj;
				// Check the file really there
				if ((toc.getMyfile() != null) && (toc.getMyfile().getName() != null))
				{
					// Save the file to local directory on the client
					Save save = new Save(toc.getMyfile(),OBLSettings.TOC_CLIENT_PATH);
					toc_msg.setSuccess(true);
					System.out.println("SubscriberUIP@Client: (handlePdfDownload) File saved on Hard Disk: " + toc.getMyfile().getName());
					
					// Open the TOC file in the client default application
					File toc_file = new File(OBLSettings.TOC_CLIENT_PATH+toc.getMyfile().getName());
					Desktop.getDesktop().open(toc_file);
				}
			}
		}
		catch (Exception e) 
		{
			System.out.println("UIP: EXCEPTION in viewSubscriberHistory ");
			e.printStackTrace();
			return toc_msg;
		}
		return toc_msg;
	}
//=============================================================================================			
	@Override
	public void update(Observable arg0, Object arg1) 
	{
		// TODO Auto-generated method stub
		System.out.println("SubscriberUIP: Recieved notify: arg0:   " + arg0.toString() + "   |   arg1: "+ arg1.toString());
	}

}//class
